/*
 * Copyright (C) 2010-2101 Alibaba Group Holding Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.otter.shared.arbitrate.impl.zookeeper;

import com.alibaba.otter.shared.arbitrate.impl.config.ArbitrateConfigUtils;
import com.alibaba.otter.shared.common.utils.zookeeper.ZkClientX;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.OtterMigrateMap;
import org.I0Itec.zkclient.IZkStateListener;
import org.apache.commons.lang.StringUtils;
import org.apache.zookeeper.Watcher.Event.KeeperState;

import java.util.Collections;
import java.util.List;

/**
 * 封装了ZooKeeper，使其支持节点的优先顺序，比如美国机房的节点会优先加载美国对应的zk集群列表，都失败后才会选择加载杭州的zk集群列表
 *
 * @author jianghang 2011-9-8 下午07:55:44
 * @version 4.0.0
 */
public class ZooKeeperClient {

    private static String cluster;
    private static int sessionTimeout = 10 * 1000;
    private static final LoadingCache<Long, ZkClientX> clients = OtterMigrateMap.makeComputingMap(pipelineId -> createClient());
    private final static Long DEFAULT_ID = 0L;

    /**
     * 获取对应的zookeeper客户端
     */
    public static ZkClientX getInstance() {
        return getInstance(DEFAULT_ID);
    }

    /**
     * 根据pipelineId获取对应的zookeeper客户端，每个pipelineId可以独立一个zookeeper链接，保证性能
     */
    public static ZkClientX getInstance(Long pipelineId) {
        return clients.getUnchecked(pipelineId);
    }

    public static void destroy() {
        for (ZkClientX zkClient : clients.asMap().values()) {
            zkClient.close();
        }
    }

    public static void registerNotification(final SessionExpiredNotification notification) {
        getInstance().subscribeStateChanges(new IZkStateListener() {

            public void handleStateChanged(KeeperState state) {

            }

            public void handleNewSession() {
                notification.notification();
            }

            @Override
            public void handleSessionEstablishmentError(Throwable error) {
            }
        });

    }

    private static ZkClientX createClient() {
        List<String> serverAddress = getServerAddrs();
        return new ZkClientX(StringUtils.join(serverAddress, ","), sessionTimeout);
    }

    /**
     * 从当前的node信息中获取对应的zk集群信息
     */
    private static List<String> getServerAddrs() {
        List<String> result = ArbitrateConfigUtils.getServerAddrs();
        if (result.isEmpty()) {
            result = Collections.singletonList(cluster);
        }
        return result;
    }

    public void setCluster(String cluster) {
        ZooKeeperClient.cluster = cluster;
    }

    public void setSessionTimeout(int timeout) {
        ZooKeeperClient.sessionTimeout = timeout;
    }

}
